// src/utils/request.js
import axios from "axios";
import router from "@/router";

const service = axios.create({
  // baseURL: 'http://cs.xmmillions.com:18082', // 👈 替换为你实际的后端地址
  baseURL: "http://cs.xmmillions.com:18082", // 👈 替换为你实际的后端地址

  timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      window.$message?.error(res.message || "请求失败"); // 可用 Element Plus 或 naive-ui 的全局 message
      // 401 未登录处理
      if (res.code === 401) {
        localStorage.removeItem("token");
        router.push("/login");
      }
      return Promise.reject(res);
    }
    return res;
  },
  (error) => {
    window.$message?.error("网络错误，请稍后重试");
    return Promise.reject(error);
  }
);

export default service;
